
const inquirer = require('inquirer');
const execSync = require('child_process').execSync;
const chalk = require('chalk');
const fs = require('fs');
const path = require('path');

const RegDelimiter = '-----report------';
const TEMPLATE = `${RegDelimiter}\n-------End--------\n`;

class Ap {
  constructor() {
  }

  static insertCommit(commit) {
    const date = new Date().toLocaleString('zh', {hour12: false});
    return `${RegDelimiter}\n${date}: ${commit}\n`;
  }

  static wr_readme(rd_split) {
    return fs.writeFileSync(path.resolve(path.resolve('./', 'README.md')), rd_split.join(''));
  }

  static publish(commit){
    const cmd = `git add . && git commit -m '${commit}' && git push origin master`;
    const pushres = execSync(cmd, {
      encoding: 'utf8'
    });
    return pushres
  }

  async push() {
    const { commit } = await inquirer.prompt([{
      type: 'input',
      name: 'commit',
      pageSize: 20,
      message: 'commit内容',
    }]);
    this.commit = commit;
    let rd = fs.readFileSync(path.resolve('./', 'README.md'), 'utf8');
    let rd_split = rd.split('\n');

    if (!rd_split.includes(RegDelimiter)) rd_split.push(TEMPLATE);

    rd_split = rd_split.reduce((res, val, index)=>{
      if(new RegExp(RegDelimiter).test(val)){
        val = Ap.insertCommit(commit);
      }
      res = res.concat([val]);
      return res;
    }, []);

    const err = Ap.wr_readme(rd_split);
    if(!err){
      Ap.publish(commit);
      console.log(chalk.green('done'));
    }
  }
};

module.exports = Ap;